package cc.magicjson.example.demo.concurrent;

import java.util.*;
import java.util.concurrent.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {
        List<List<String>> wordLists = Arrays.asList(Arrays.asList("hello", "world"),
                Arrays.asList("java", "concurrency"),
                Arrays.asList("example", "code"));
        ExecutorService executor = Executors.newFixedThreadPool(4);
        // 类似于原始代码的处理逻辑
        LinkedList<CompletableFuture<List<String>>> completableFutures = new LinkedList<>();
        Function<String, String> convertFunction = String::toUpperCase;
        for (List<String> list : wordLists) {
            CompletableFuture<List<String>> completableFuture = CompletableFuture.supplyAsync(() ->
                            list.stream().map(convertFunction).collect(Collectors.toList()),
                    executor);
            completableFutures.add(completableFuture);
        }
//        不加allOf(...).join();返回的结果 [[HELLO, WORLD], [JAVA, CONCURRENCY], [EXAMPLE, CODE]
//
//        加allOf(...).join()返回的结果 [[HELLO, WORLD], [JAVA, CONCURRENCY], [EXAMPLE, CODE]]
        CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0])).join();

        List<List<String>> result = completableFutures.stream()
                .map(CompletableFuture::join)
                .collect(Collectors.toList());
        System.out.println(result);  // 输出：[[HELLO, WORLD], [JAVA, CONCURRENCY], [EXAMPLE, CODE]]
        executor.shutdown();
    }
}